import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useTokenStore } from '@/stores/token.js'

const baseURL = 'http://localhost:8088'
const instance = axios.create({ baseURL })

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const tokenStore = useTokenStore()
    if (tokenStore.token) {
      config.headers.Authorization = tokenStore.token
    }
    else if (localStorage.getItem('token')) {
        config.headers.Authorization = localStorage.getItem('token')
    }else if (config.url !== '/acUser/login') {
      router.push('/login')
      return Promise.reject('请先登录')
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.success) {
      return res
    }
    ElMessage.error(res.message || '服务异常')
    return Promise.reject(res)
  },
  (error) => {
    if (error.response?.status === 401) {
      const tokenStore = useTokenStore()
      tokenStore.removeToken()
      router.push('/login')
      ElMessage.error('登录已过期，请重新登录')
    } else {
      ElMessage.error(error.message || '服务异常')
    }
    return Promise.reject(error)
  }
)

export default instance
